<?php
namespace app\api\controller;
use app\common\lib\Export;
use app\common\lib\Request;
use app\common\lib\Code;
use think\Exception;
use think\facade\Config;
use app\api\model\User;
use think\facade\Validate;
use app\common\facade\WebSocketToken;


class Login extends Base
{

    private $cmd_data = [
        //检验账号是否存在
        "100"=>"check_mobile",
        //获取手机验证码
        "101"=>"get_mobile_code",
        //注册账号
        "102"=>"registered",
        //登录
        "103"=>"login",
        //获取邮箱验证码
        '104'=>'get_email_code',
        //获取websocket登录token
        '105'=>'get_socket_token',
    ];
    /** 入口 */
    public function index(){
        try{
            $cmd = Request::get('cmd');
            $method = $this->cmd_data[$cmd];
            $this->$method();
        }catch (Exception $e){
            Export::exp_err($e->getMessage(),$e->getCode());
        }
        return '';
    }
    /** 检验手机号是否已存在 */
    private function check_mobile(){
        $data = Request::post(["mobile"]);
        $data['mobile'] = 18814142694;
        // 校验手机号
        $this->validate_mobile($data['mobile']);
        //检验手机号是否已存在
        $user = User::where(['mobile'=>$data['mobile']])->find();
        $flag = $user ? 1:0;
        Export::exp_ok(["flag"=>$flag]);
    }

    /** 手机获取验证码 */
    private function get_mobile_code(){
        $data = Request::post(["mobile"]);
        // 校验手机号
        $this->validate_mobile($data['mobile']);

        //验证码
        $key = md5($data['mobile']."_code");
        $code = Code::set_code($key);
        Export::exp_ok(['code'=>$code]);
    }
    /** 邮箱获取验证码 */
    private function get_email_code(){
        $data = Request::post(["email"]);
        // 校验手机号
        $this->validate_email($data['email']);

        //验证码
        $key = md5($data['email']."_code");
        $code = Code::set_code($key);
        Export::exp_ok(['code'=>$code]);
    }
    /** 103 登录账号 */
    private function login(){
        $data = Request::post(["mobile"]);
        $type = array_key_exists('type',$data)?$data['type']:0;

        //查看手机号是否已注册
        $user = User::where(['mobile'=>$data['mobile']])->find();
        if(!$user) throw new Exception("该手机号未注册!");

        // 默认登录方式：密码登录；1：验证码登录
        switch ($type){
            case 1:
                //校验验证码
                if(!array_key_exists('code',$data)) throw new Exception("参数错误!");
                if(!$data['code']) throw new Exception("请输入验证码!");
                $key = md5($data['mobile']."_code");
                Code::check_code($key,$data['code']);
                break;
            default:
                if(!array_key_exists('password',$data)) throw new Exception("参数错误!");
                if(md5($data['password'])!=$user['password']) throw new Exception("账号或密码不正确!");
                break;
        }
        //保存用户信息
        parent::set_user_info($user);

        //websocket 登录token
        $token = $this->set_websocket_token($user->id);

        $info = [
            "token"=>$token
        ];
        Export::exp_ok($info);
    }
    /** 注册账号 */
    private function registered(){
        $data = Request::post(["code","mobile","password"]);

        // 校验手机号
        $this->validate_mobile($data['mobile']);
        // 检验手机号是否已存在
        $user = User::where(['mobile'=>$data['mobile']])->find();
        if($user){
            throw new Exception("该手机号已注册");
        }
        //验证验证码
        $key = md5($data['mobile']."_code");
        Code::check_code($key,$data['code']);

        // 保存至数据库
        $user = User::create([
            "mobile"=>$data['mobile'],
            "password"=>$data['password'],
            "name"=>"用户".rand(1000000000,9999999999),
            "pic_url"=>get_portrait(),
        ]);

        //保存登录信息
        parent::set_user_info($user);

        //websocket 登录token
        $token = $this->set_websocket_token($user->id);

        $info = [
            "token"=>$token
        ];
        Export::exp_ok($info);
    }



    private function auth()
    {
        $app_id = Config::get("weixin.appid");
        $redirect_uri = url('api/Login/login');
        $url = WeiXin::authorize($redirect_uri,$app_id);

        $this->redirect($url);
    }





    /** 内部实现方法 */

    /** 校验手机号 */
    private function validate_mobile($mobile){
        // 校验手机号
        Validate::rule(['mobile'=>"mobile"]);
        if(!Validate::check(["mobile"=>$mobile])) throw new Exception("请输入正确的手机号！");
        return true;
    }
    /** 校验邮箱 */
    private function validate_email($email){
        // 校验邮箱
        Validate::rule(['email'=>"email"]);
        if(!Validate::check(["email"=>$email])) throw new Exception("请输入正确的邮箱！");
        return true;
    }
    /** 保存websocket token */
    private function set_websocket_token($id){
        $token = WebSocketToken::set($id);
        return $token;
    }
}
